package com.mall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.uitl.JWTTokenUtil;
import com.mall.uitl.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


@Component
public class LoginValidateInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JWTTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在请求到达action前，先执行preHandle方法，该方法返回true,会调用相应的action,返回false就不调用相应的action了
        //需要用方法的形参response返回结果给前端
        logger.debug("preHandle方法被调用");
        try {
            String loginuserJson = jwtTokenUtil.getDecodeToken(request);
            logger.debug("前端传递过来的JWT解密后的结果为:"+loginuserJson);
            return true;
        }catch (Exception e){

            logger.error("判断用户是否登录校验失败:",e);
            ObjectMapper objectMapper = new ObjectMapper();

            response.setContentType("text/html;charset=utf-8");
            PrintWriter out =  response.getWriter();
            JsonUtil jsonUtil = new JsonUtil();
            jsonUtil.setCode(999);
            jsonUtil.setMsg("您还未登录，请先登录");

            out.println( objectMapper.writeValueAsString(jsonUtil));
            return false;
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.debug("postHandle方法被调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.debug("postHandle方法被调用");
    }
}
